package vn.gq.tym.widget.tab;

import vn.gq.tym.widget.ITabHost;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;


public abstract class BaseFragment extends SherlockFragment {
	
	public static final String PREV_TAG_KEY = "PREV_TAG";
	
	protected ViewGroup mLayout;
	
	public abstract int getContainerId();
	
	public abstract int getLayoutId();
	
	public abstract void createView();
	
	public void setPrevFragmentTag(String tag) {
		Bundle args = getArguments();
		args.putString("PREV_TAG", tag);
		setArguments(args);
	}
	
	public String getPrevFragmentTag() {
		if (getArguments() != null) {
			return getArguments().getString(PREV_TAG_KEY);
		}
		return "";
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLayout = (ViewGroup) inflater.inflate(getLayoutId(), container, false);
		createView();
		return mLayout;
	}
	
	public View findViewById(int resId) {
		return mLayout.findViewById(resId);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		((ITabHost) getActivity()).setCurrentFragment(this);
	}

	public void startFragment(int containerId, Fragment fragment, String tag) {
		((BaseFragment) fragment).setPrevFragmentTag(tag);
		FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
		transaction.detach(this);
		transaction.add(containerId, fragment, tag);
		transaction.commit();
	}
	
	public boolean canBack() {
		if (getPrevFragmentTag().equals("")) return false;
		Fragment prevFragment = getActivity().getSupportFragmentManager().findFragmentByTag(getPrevFragmentTag());
		if (prevFragment == null) return false;
		return true;
	}
	
	public void onBackPressed() {
		
		Log.i("Fragment", "--------PrevTag: "+getPrevFragmentTag());
		
		BaseFragment prevFragment = (BaseFragment) getActivity().getSupportFragmentManager().findFragmentByTag(getPrevFragmentTag());
		if (prevFragment != null) {
			FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
			ft.remove(this);
			ft.add(prevFragment.getContainerId(), prevFragment);
			ft.commit();
		} else {
			getActivity().finish();
		}
	}
}
